/*
 * Copyright 2013-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.cyx.netty.gateway.route;

import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import reactor.core.publisher.Flux;


// 路由定位器的包装类，实现了路由的本地缓存功能
public class CachingRouteLocator implements RouteLocator {
	//目标路由定位器
	private final RouteLocator delegate;

	/**
	 * 路由信息
	 * Flux 相当于一个 RxJava Observable，
	 * 能够发出 0~N 个数据项，然后（可选地）completing 或 erroring。处理多个数据项作为stream
	 */
	private final AtomicReference<List<Route>> cachedRoutes = new AtomicReference<>();

	public CachingRouteLocator(RouteLocator delegate) {
		this.delegate = delegate;
		this.cachedRoutes.compareAndSet(null, collectRoutes());
	}

	@Override
	public Flux<Route> getRoutes() {
		return Flux.fromIterable(this.cachedRoutes.get());
	}

	/**
	 * Sets the new routes
	 * @return old routes
	 */    // 刷新缓存
	public Flux<Route> refresh() {
		return Flux.fromIterable(this.cachedRoutes.getAndUpdate(
				routes -> CachingRouteLocator.this.collectRoutes()));
	}

	private List<Route> collectRoutes() {
		List<Route> routes = this.delegate.getRoutes().collectList().block();
		AnnotationAwareOrderComparator.sort(routes);
		return routes;
	}

}
